package com.wwinsoft.framework.service.system;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wwinsoft.framework.dao.system.CodeDao;
import com.wwinsoft.framework.dao.system.CodeTypeDao;
import com.wwinsoft.framework.entity.system.Code;
import com.wwinsoft.framework.entity.system.CodeType;
import com.wwinsoft.modules.orm.Page;
import com.wwinsoft.modules.orm.PropertyFilter;

@Service
@Transactional
@SuppressWarnings(value = { "unchecked" })
public class CodeManager {
    @Autowired
    private CodeDao codeDao;

    @Autowired
    private CodeTypeDao codeTypeDao;

    @Transactional(readOnly = true)
    public Code getCodeByTypeAndCodeValue(String codeType, String codeValue) {
        return codeDao.getCodeByTypeAndCodeValue(codeType, codeValue);
    }

    @Transactional(readOnly = true)
    public List<Code> getCodeListByType(String codeType) {
        return codeDao.getCodeListByType(codeType);
    }

    @Transactional(readOnly = true)
    public List<CodeType> getCodeTypeList() {
        return codeTypeDao.getCachedAll();
    }

    @Transactional(readOnly = true)
    public List<CodeType> getMaintainedCodeTypeList() {
        return codeTypeDao.getCachedMaintainedAll();
    }

    @Transactional(readOnly = true)
    public Page<Code> searchCode(final Page<Code> page, final List<PropertyFilter> filters) {
        return codeDao.findDetachedPage(page, filters);
    }

    @Transactional(readOnly = true)
    public Code getCode(Long id) {
        return codeDao.get(id);
    }

    public Object formatCodeValue(String codeType, Object codeValue) {
        if (StringUtils.isEmpty(codeType) || codeValue == null) {
            return codeValue;
        }
        Code code = codeDao.getCodeByTypeAndCodeValue(codeType, String.valueOf(codeValue));
        if (code == null) {
            return codeValue;
        } else {
            return code.getCode();
        }
    }

    public void saveCode(Code code) {
        codeDao.save(code);
    }

    public void deleteCode(Long id) {
        codeDao.delete(id);
    }

    @Transactional(readOnly = true)
    public List<Code> getCodeListByTable(String table, String codeColumn, String valueColumn, String where) {
        return codeDao.getCodeListByTable(table, codeColumn, valueColumn, where);
    }

    @Transactional(readOnly = true)
    public Code getCodeByTable(String table, String codeColumn, String valueColumn, String where, String codeValue) {
        return codeDao.getCodeByTable(table, codeColumn, valueColumn, where, codeValue);
    }


}